package com.myCommunity.ui;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.myCommunity.dao.impl.ForumDaoImpl;
import com.myCommunity.dao.impl.TopicDaoImpl;
import com.myCommunity.entity.Forum;
import com.myCommunity.entity.Topic;
import com.myCommunity.entity.Users;

public class ForumServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		Users user = (Users) request.getSession().getAttribute("user");

		request.setAttribute("user", user);
				
		int forumId = 0 ;
		if(request.getParameter("forumId") != null && !request.getParameter("forumId").isEmpty())
			forumId = Integer.parseInt(request.getParameter("forumId"));
		
		request.setAttribute("forumId", forumId);
		
		//根据讨论区id查询讨论区信息
		Forum f = new ForumDaoImpl().getForumById(forumId);
		request.setAttribute("forum", f);
		
		//根据forumid分类查询精华帖和普通贴
		int pageNum = 1;
		int pageSize = 5;
		
		if(request.getParameter("pageNum") != null && !request.getParameter("pageNum").isEmpty())
			pageNum = Integer.parseInt(request.getParameter("pageNum"));
	
		//总页数
		int totalPage = 0;
		int cPage = (int)Math.ceil((double)new TopicDaoImpl().getTopicSize(0,forumId)/pageSize);
		int ePage = (int)Math.ceil((double)new TopicDaoImpl().getTopicSize(1,forumId)/pageSize);
		if(cPage>ePage)
			totalPage = cPage;
		else
			totalPage = ePage;
		
		//普通区
		List<Topic> common = new TopicDaoImpl().getTopicListByForumId(pageNum, pageSize, forumId, 0);
		request.setAttribute("common", common);
		
		//精华区
		List<Topic> essence = new TopicDaoImpl().getTopicListByForumId(1, pageSize, forumId, 1);
		request.setAttribute("essence", essence);
		
		request.setAttribute("cPage", cPage);
		request.setAttribute("ePage", ePage);
		request.setAttribute("pageNum", pageNum);
		request.setAttribute("totalPage", totalPage);
		request.getRequestDispatcher("forum.jsp").forward(request, response);
	}
	
	public static void main(String[] args) {
		List<Topic> common = new TopicDaoImpl().getTopicListByForumId(1, 5, 3, 0);
			for(Topic c:common)
				System.out.println(c.getTitle());

	}

}
